package com.fuhe.chen.vendingmachine.controller.app;

import com.fuhe.chen.vendingmachine.dto.ApiResponseForList;
import com.fuhe.chen.vendingmachine.common.Utils;
import com.fuhe.chen.vendingmachine.common.redis.RedisUtils;
import com.fuhe.chen.vendingmachine.dto.cond.CommodityCond;
import com.fuhe.chen.vendingmachine.pojo.Commodity;
import com.fuhe.chen.vendingmachine.pojo.CommoditySellLabel;
import com.fuhe.chen.vendingmachine.service.ICommoditySellLabelService;
import com.fuhe.chen.vendingmachine.service.ICommodityService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/app/commodityInfo")
@ResponseBody
@Api(tags = "商品信息接口(面向app)")
public class CommodityInfoController {

    public static final String HISTORY_SEARCH = "HistorySearch:";

    public static final Integer SEARCH_CACHE_SAVE_VALVE = 2;

    Map<String,Integer> historySearch = new HashMap<>();

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ICommodityService commodityService;

    @Autowired
    ICommoditySellLabelService sellLabelService;


    private int count = 0;


    /**
     * 根据商品标签查询商品列表
     */
    @ApiOperation(value = "根据商品标签查询商品列表",notes = "返回json格式数据")
    @GetMapping("api/getCommodityListByLabelId/{labelId}/{pageNum}/{pageSize}")
    @ResponseBody
    public ApiResponseForList<Commodity> getCommodityListByLabelId(@PathVariable Integer labelId,
                                                                   @PathVariable Integer pageNum,
                                                                   @PathVariable Integer pageSize
                                            ){
        PageInfo<Commodity> allRelationshipByLabel = sellLabelService.findCommodityPageByLabel(labelId, pageNum, pageSize);

        ApiResponseForList<Commodity> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(allRelationshipByLabel.getList());

        return response;
    }

    @ApiOperation(value = "根据商品分类id和页数获取商品信息")
    @GetMapping({"/getCommodityInfoByCategory/{category_id}/{pageNum}"})
    public ApiResponseForList<Commodity> getCommodityInfoByCategory(@PathVariable Integer category_id, @PathVariable Integer pageNum){
        List<Commodity> list = getCommodityList(category_id,null, pageNum);

        ApiResponseForList<Commodity> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(list);

        return response;
    }


    @ApiOperation(value = "根据商品名称和页数获取商品信息")
    @GetMapping({"/getCommodityInfoByName/{commodityName}/{pageNum}"})
    public ApiResponseForList<Commodity> getCommodityInfoByName(@PathVariable String commodityName, @PathVariable Integer pageNum){
        setHistorySearch(commodityName);
        List<Commodity> list =  getCommodityList(null,commodityName.trim(),pageNum);

        ApiResponseForList<Commodity> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(list);

        return response;
    }


    private List<Commodity> getCommodityList(Integer category_id, String commodityName, Integer pageNum) {
        CommodityCond cond = new CommodityCond();
        cond.setCategory(category_id);
        cond.setCommodity_name(commodityName);
        cond.setCommodity_status(1);
        PageInfo<Commodity> commodityPageInfo = commodityService.queryCommodityByCondition(cond, pageNum, 10);
        List<Commodity> list = commodityPageInfo.getList();
        return list;
    }


    /**
     * 记录历史搜索
     * 当总搜索次数超过SEARCH_CACHE_SAVE_VALVE时,将搜索记录保存到redis中
     * @param commodityName
     */
    private void setHistorySearch(@PathVariable String commodityName) {
         if(redisUtils.hasKey(HISTORY_SEARCH)){
            historySearch = (Map<String, Integer>) redisUtils.get(HISTORY_SEARCH);
        }
        if(!historySearch.containsKey(commodityName)){
            historySearch.put(commodityName,1);
        }else{
            Integer searchCount = historySearch.get(commodityName);
            historySearch.put(commodityName, ++searchCount);
        }
        count++;
        if(count==SEARCH_CACHE_SAVE_VALVE){
            redisUtils.set(HISTORY_SEARCH,historySearch);
            count = 0;
        }
    }


    @ApiOperation(value = "获取搜索热词")
    @GetMapping({"/hotSearch"})
    public ApiResponseForList<String> getHotSearch() {
        if(redisUtils.hasKey(HISTORY_SEARCH)){
            historySearch = (Map<String, Integer>) redisUtils.get(HISTORY_SEARCH);
        }
        List<Map.Entry<String, Integer>> list = new ArrayList<>();
        List<String> hotSearch = new ArrayList<>();
        list.addAll(historySearch.entrySet());

        ValueComparator valueComparator = new ValueComparator();
        Collections.sort(list,valueComparator);

        for (Map.Entry<String, Integer> entry : list) {
            hotSearch.add(entry.getKey());
            if(hotSearch.size()==10){
                break;
            }
        }

        ApiResponseForList<String> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(hotSearch);

        return response;
    }



    @ApiOperation(value = "根据id获取商品详情")
    @GetMapping({"/getDetail/{id}"})
    public ApiResponseForList<Commodity> getCommodityDetail(@PathVariable Integer id) {
        //是否上架判断
        Boolean isCommodityOnSale = Utils.isCommodityOnSale(id, commodityService);

        ApiResponseForList<Commodity> response = new ApiResponseForList<>();
        List<Commodity> data  = new ArrayList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        if(isCommodityOnSale){
            Commodity commodity = commodityService.queryOne(id);
            data.add(commodity);
            response.setData(data);
        }
        return response;
    }


    @ApiOperation(value = "获取全部营销标签", notes="返回json格式数据")
    @GetMapping({"/getAllLabel"})
    @ResponseBody
    public ApiResponseForList<CommoditySellLabel> getAllLabel(){
        List<CommoditySellLabel> all = sellLabelService.findAll();

        ApiResponseForList<CommoditySellLabel> response = new ApiResponseForList<>();
        response.setSuccess(true);
        response.setCode(10000);
        response.setMessage("调用成功");
        response.setData(all);
        return response;
    }

    private static class ValueComparator implements Comparator<Map.Entry<String, Integer>> {
        public int compare(Map.Entry<String, Integer> m, Map.Entry<String, Integer> n) {
            return n.getValue().compareTo(m.getValue());
        }
    }
}
